package com.frank.redis;

import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.pool.impl.GenericObjectPool;
import org.apache.commons.pool.impl.GenericObjectPool.Config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.context.ApplicationContext;

import redis.clients.jedis.JedisShardInfo;
import redis.clients.jedis.ShardedJedisPool;
//import redis.clients.jedis.ShardedJedisPool.ShardedJedisFactory;

import com.frank.redis.shard.JedisCluster;
import com.frank.redis.shard.ShardInfo;
import com.frank.redis.spring.JedisBeanFactoryPostProcessor;
import com.frank.redis.spring.JedisPoolBean;
import com.frank.zk.ZooKeeperManager;

import static com.frank.redis.spring.JedisPoolBean.BEAN_PREFIEX;

/**
 * 
 * @author liushaomingdev@163.com
 *
 */
public class JedisPoolFactory implements InitializingBean {

	private static Logger LOG = LoggerFactory.getLogger(JedisPoolFactory.class);

	private static Map<String, JedisPoolBean> POOLS = null;

	private Config poolConfig;

	@Resource(name = "redis_zkConf")
	private Map<String, String> zkConf;

	@Value("#{redis_conf['host'] ?: 'localhost'}")
	private String host;

	@Value("#{redis_conf['port'] ?: 6379}")
	private Integer port;

	@Value("#{redis_conf['password']}")
	private String password;

	public static ShardedJedisPool getPool(String poolCategory) {
		if (POOLS == null) {
			synchronized (JedisPoolFactory.class) {
				JedisBeanFactoryPostProcessor.getJedisPoolFactory();
			}
		}

		JedisPoolBean pool = POOLS.get(poolCategory);
		if (pool == null)
			LOG.warn("get pool {} fail", poolCategory);
		return pool;
	}

	public static void loadServers(Collection<? extends JedisShardInfo> nodes) {
		for (JedisPoolBean pool : POOLS.values())
			pool.load(nodes);
	}

	public static void loadServers(Collection<ShardInfo> nodes, String zkName) {
		for (JedisPoolBean pool : POOLS.values()) {
			if (zkName.equals(pool.getZkName()))
				pool.load(nodes);
		}
	}
	

	public GenericObjectPool createPool(ShardedJedisFactory factory) {
		return new GenericObjectPool(factory, poolConfig);
	}

	@Autowired
	ApplicationContext context;

	@Override
	public void afterPropertiesSet() throws Exception {
		poolConfig = new Config();
		poolConfig.testOnBorrow = true;
		poolConfig.testWhileIdle = true;

		if (StringUtils.isBlank(password))
			password = null;

		Map<String, JedisPoolBean> pools = new HashMap<String, JedisPoolBean>();
		try {
			Map<String, JedisPoolBean> beans = context.getBeansOfType(JedisPoolBean.class);
			if (beans == null || beans.isEmpty())
				return;

			AutowireCapableBeanFactory factory = context.getAutowireCapableBeanFactory();
			for (Map.Entry<String, JedisPoolBean> entry : beans.entrySet()) {
				String name = entry.getKey();
				if (name.startsWith(BEAN_PREFIEX))
					name = name.substring(BEAN_PREFIEX.length());

				factory.autowireBean(entry.getValue());
				pools.put(name, entry.getValue());
			}
			POOLS = Collections.unmodifiableMap(pools);
			LOG.info("init jedis pools, size:{}", pools.size());
			LOG.debug("init jedis pools: {}", pools.keySet());

			if (zkConf == null || zkConf.isEmpty()) {
				LOG.info("zkconf null: host-{}, port-{}", host, port);
				JedisShardInfo shard = new JedisShardInfo(host, port);
				shard.setPassword(password);
				loadServers(Arrays.asList(shard));
				return;
			}

			factory.getBean(ZooKeeperManager.class);
			for (Map.Entry<String, String> entry : zkConf.entrySet()) {
				String name = entry.getKey();
				String root = entry.getValue();
				new JedisCluster(root, name, password);
			}
			LOG.info("init {} zookeeper group for jedis", zkConf.size());
		} catch (Exception e) {
			LOG.error("JedisPoolFactory init error", e);
		} finally {
			POOLS = Collections.unmodifiableMap(pools);
		}
	}
}
